<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Monaco Editor 多文件示例</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.44.0/min/vs/loader.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .app-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        
        .file-explorer {
            width: 250px;
            background-color: #2d2d2d;
            color: #ccc;
            padding: 10px;
            overflow-y: auto;
        }
        
        .file-explorer h3 {
            color: #fff;
            padding: 10px 0;
            margin: 0;
            border-bottom: 1px solid #444;
        }
        
        .file-item {
            padding: 8px 10px;
            cursor: pointer;
            border-radius: 4px;
            margin: 2px 0;
            display: flex;
            align-items: center;
        }
        
        .file-item:hover {
            background-color: #444;
        }
        
        .file-item.active {
            background-color: #007acc;
            color: white;
        }
        
        .file-item i {
            margin-right: 8px;
            width: 16px;
            text-align: center;
        }
        
        .editor-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .tabs {
            display: flex;
            background-color: #2d2d2d;
            padding: 0 10px;
            border-bottom: 1px solid #444;
            overflow-x: auto;
        }
        
        .tab {
            padding: 8px 15px;
            color: #ccc;
            cursor: pointer;
            display: flex;
            align-items: center;
            border-right: 1px solid #444;
        }
        
        .tab.active {
            background-color: #1e1e1e;
            color: white;
        }
        
        .tab-close {
            margin-left: 8px;
            font-size: 12px;
        }
        
        .tab-close:hover {
            color: #ff4444;
        }
        
        #editor {
            flex: 1;
        }
        
        .controls {
            padding: 10px;
            background-color: #f5f5f5;
            border-bottom: 1px solid #ddd;
        }
        
        button {
            padding: 6px 12px;
            margin-right: 10px;
            cursor: pointer;
            background-color: #007acc;
            color: white;
            border: none;
            border-radius: 4px;
        }
        
        button:hover {
            background-color: #005fa3;
        }
    </style>
</head>
<body>
    <div class="controls">
        <button id="newFileBtn"><i class="fas fa-file"></i> 新建文件</button>
        <button id="newFolderBtn"><i class="fas fa-folder"></i> 新建文件夹</button>
    </div>
    
    <div class="app-container">
        <div class="file-explorer">
            <h3>文件结构</h3>
            <div id="fileTree">
                <!-- 文件树将在这里动态生成 -->
            </div>
        </div>
        
        <div class="editor-container">
            <div class="tabs" id="tabsContainer">
                <!-- 标签页将在这里动态生成 -->
            </div>
            <div id="editor"></div>
        </div>
    </div>

    <script>
        // 存储文件数据
        const files = {
            'main.js': {
                content: 'console.log("Hello, World!");\n\nfunction add(a, b) {\n    return a + b;\n}',
                language: 'javascript'
            },
            'utils.py': {
                content: 'def greet(name):\n    return f"Hello, {name}!"',
                language: 'python'
            },
            'README.md': {
                content: '# 项目说明\n\n这是一个多文件编辑示例',
                language: 'markdown'
            }
        };
        
        let currentFile = 'main.js';
        let editor;
        
        // 初始化Monaco Editor
        require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.44.0/min/vs' } });
        require(['vs/editor/editor.main'], function() {
            editor = monaco.editor.create(document.getElementById('editor'), {
                value: files[currentFile].content,
                language: files[currentFile].language,
                theme: 'vs-dark',
                automaticLayout: true
            });
            
            // 当编辑器内容变化时更新文件内容
            editor.onDidChangeModelContent(() => {
                files[currentFile].content = editor.getValue();
            });
            
            // 初始化文件树和标签页
            updateFileTree();
            updateTabs();
        });
        
        // 更新文件树
        function updateFileTree() {
            const fileTree = document.getElementById('fileTree');
            fileTree.innerHTML = '';
            
            Object.keys(files).forEach(filename => {
                const fileItem = document.createElement('div');
                fileItem.className = `file-item ${filename === currentFile ? 'active' : ''}`;
                
                // 根据文件类型选择图标
                let icon = 'file';
                if (filename.endsWith('.js')) icon = 'file-code';
                else if (filename.endsWith('.py')) icon = 'file-code';
                else if (filename.endsWith('.md')) icon = 'file-markdown';
                
                fileItem.innerHTML = `<i class="fas fa-${icon}"></i> ${filename}`;
                fileItem.addEventListener('click', () => openFile(filename));
                fileTree.appendChild(fileItem);
            });
        }
        
        // 更新标签页
        function updateTabs() {
            const tabsContainer = document.getElementById('tabsContainer');
            tabsContainer.innerHTML = '';
            
            Object.keys(files).forEach(filename => {
                const tab = document.createElement('div');
                tab.className = `tab ${filename === currentFile ? 'active' : ''}`;
                tab.innerHTML = `${filename} <span class="tab-close"><i class="fas fa-times"></i></span>`;
                
                // 点击标签切换文件
                tab.addEventListener('click', (e) => {
                    if (!e.target.closest('.tab-close')) {
                        openFile(filename);
                    }
                });
                
                // 点击关闭按钮关闭文件
                tab.querySelector('.tab-close').addEventListener('click', (e) => {
                    e.stopPropagation();
                    closeFile(filename);
                });
                
                tabsContainer.appendChild(tab);
            });
        }
        
        // 打开文件
        function openFile(filename) {
            // 保存当前文件内容
            if (currentFile) {
                files[currentFile].content = editor.getValue();
            }
            
            // 切换到新文件
            currentFile = filename;
            editor.setValue(files[filename].content);
            monaco.editor.setModelLanguage(editor.getModel(), files[filename].language);
            
            // 更新UI
            updateFileTree();
            updateTabs();
        }
        
        // 关闭文件
        function closeFile(filename) {
            // 不能关闭最后一个文件
            if (Object.keys(files).length <= 1) {
                alert('至少保留一个文件');
                return;
            }
            
            // 如果关闭的是当前文件，切换到第一个文件
            if (filename === currentFile) {
                const remainingFiles = Object.keys(files).filter(f => f !== filename);
                currentFile = remainingFiles[0];
                editor.setValue(files[currentFile].content);
                monaco.editor.setModelLanguage(editor.getModel(), files[currentFile].language);
            }
            
            // 删除文件
            delete files[filename];
            
            // 更新UI
            updateFileTree();
            updateTabs();
        }
        
        // 新建文件
        document.getElementById('newFileBtn').addEventListener('click', () => {
            const filename = prompt('请输入文件名（如：newfile.js）:');
            if (!filename) return;
            
            // 检查文件是否已存在
            if (files[filename]) {
                alert('文件已存在');
                return;
            }
            
            // 确定文件语言
            let language = 'plaintext';
            if (filename.endsWith('.js')) language = 'javascript';
            else if (filename.endsWith('.py')) language = 'python';
            else if (filename.endsWith('.html')) language = 'html';
            else if (filename.endsWith('.css')) language = 'css';
            else if (filename.endsWith('.md')) language = 'markdown';
            
            // 添加新文件
            files[filename] = {
                content: '',
                language: language
            };
            
            // 打开新文件
            openFile(filename);
        });
        
        // 新建文件夹（简化实现，实际需要更复杂的逻辑）
        document.getElementById('newFolderBtn').addEventListener('click', () => {
            const foldername = prompt('请输入文件夹名:');
            if (foldername) {
                alert(`文件夹功能：已创建 "${foldername}"（实际实现需要更复杂的文件树逻辑）`);
            }
        });
    </script>
</body>
</html>
